package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author: atguigu
 * @create: 2024-08-02 15:40
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private VodService vodService;

    /**
     * 图片（封面、头像）文件上传
     * 前端提交文件参数名：file
     *
     * @param multipartFile
     * @return
     */
    @Override
    public String fileUpload(MultipartFile multipartFile) {
        //1.业务校验验证图片内容格式是否合法
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(multipartFile.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (bufferedImage == null) {
            throw new GuiguException(400, "文件格式有误");
        }
        //2.业务校验-验证图片大小合法
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if (width > 900 || height > 900) {
            throw new GuiguException(400, "文件大小有误！");
        }
        //TODO 校验图片内容是否合法-判断图片是否存在违规
        String suggest = vodService.scanImage(multipartFile);
        if (!"pass".equals(suggest)) {
            throw new GuiguException(500, "图片内容非法！");
        }
        try {
            //3.将文件上传到MInIO
            //3.1 生成带有文件夹目录文件名称 形式：/日期/随机文件名称.后缀
            String folder = "/" + DateUtil.today();
            String fileName = IdUtil.randomUUID();
            String extName = FileNameUtil.extName(multipartFile.getOriginalFilename());
            String objName = folder + "/" + fileName + "." + extName;
            //3.2 调用minio客户对象上传文件方法
            String bucketName = minioConstantProperties.getBucketName();
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objName).stream(
                                    multipartFile.getInputStream(), multipartFile.getSize(), -1)
                            .contentType(multipartFile.getContentType())
                            .build());
            //3.3 拼接上传文件在线路径地址
            return minioConstantProperties.getEndpointUrl() + "/" + bucketName + objName;
        } catch (Exception e) {
            throw new GuiguException(500, "文件上传失败");
        }
    }
}
